<template>
	<view>
		<button @click="startPrint('1834464603254427648')" :loading="printLoading">打印</button>
		<!-- 动态创建webview -->
		<web-view
			ref="webview"
			:src="webviewSrc"
			:update-title="false"
			:fullscreen="false"
			:webview-styles="{
				width: '100px',
				height:'100px'
			}"
			@message="message"
		></web-view>
		
		<view class="">
			<view class="u-m-t-50" v-for="item in mockList" :key="item.id">
				<text class="u-padding-20">周转码：{{item.externalCode}}</text>
				<button type="default" @click="startPrint(item)">打印</button>
			</view>
		</view>
		<u-modal :show="showImport" ref="uModal" :content="showImportContent"
			confirmText="确认" showCancelButton :asyncClose="true" @cancel="cancelImport"
			@confirm="confirmImport(selectOrder)"></u-modal>
	</view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';

const printerDevice = 'ZDesigner ZT231-203dpi ZPL';
const mockList = [{
	id: '1834829157738090496',
	externalCode: '202409130004'
}, {
	id: '1834771485357641728',
	externalCode: '202409120095'
}]
const url = `${process.env.VITE_APP_WEBVIEW}iframePrint`;
// const url = 'http://192.168.3.61:3000/#/iframePrint';
const webviewSrc = ref(url);
const printLoading = ref(false);

const webview = ref();

// webview向外部发送消息
function message(event) {
	showImport.value = false;
	const data = event.detail.data[0];
	if (data.code === 200) {
		uni.showToast({
			icon: 'none',
			title:data.message,
		})
	} else {
		uni.showToast({
			icon: 'none',
			title:data.message,
		})
	}
	console.log("接收到消息：" + JSON.stringify(event.detail.data));
}

const showImport = ref(false)
const showImportContent = ref('')

watch(()=>showImport.value,(newValue)=>{
	if (newValue === false) {
		webviewSrc.value = url;
		selectOrder.value = {};
	}
})
const selectOrder = ref()

// 请确认是否打印操作
function startPrint(item:any) {
	selectOrder.value = item
	showImport.value = true
	showImportContent.value = `当前外部编号为${item?.externalCode ?? ''}, 请确认是否打印？`
}

// 开始打印
function confirmImport(item) {
	webviewSrc.value = `${url}?id=${item.id}&printer=${printerDevice}`
	showImportContent.value = `打印中，请稍等...`
}

// 取消选择订单
function cancelImport() {
	showImport.value = false;
	selectOrder.value = {};
}
</script>

<style></style>